<?php

namespace App\Admin\Controllers;

use App\Admin\Repositories\PositionMonthSalary;
use App\Admin\Services\ErpRepairSettlementService;
use App\Admin\Services\UserMonthTargetService;
use App\Models\PositionMonthTargetItem;
use App\Models\Store;
use App\Models\UserMonthAwardPunish;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;

class PositionMonthSalaryController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(PositionMonthSalary::with(['user']), function (Grid $grid) {
            $grid->column('id')->sortable();
            $grid->column('target_date');
            $grid->column('store_title', admin_trans('position-month-salary.fields.store_title'))->display(function () {
                return $this->user->store->title;
            });
            $grid->column('department_title', admin_trans('position-month-salary.fields.department_title'))->display(function () {
                return $this->user->department->title;
            });
            $grid->column('position_title', admin_trans('position-month-salary.fields.position_title'))->display(function () {
                return $this->user->position->title;
            });
            $grid->column('user.name', admin_trans('position-month-salary.fields.user_id'));

            $grid->disableCreateButton();
            $grid->disableEditButton();
            $grid->disableDeleteButton();

            $titles = [
                'id' => 'ID',
                'target_date' => admin_trans('position-month-salary.fields.target_date'),
                'store_title' => admin_trans('position-month-salary.fields.store_title'),
                'department_title' => admin_trans('position-month-salary.fields.department_title'),
                'position_title' => admin_trans('position-month-salary.fields.position_title'),
                'erp_meet_car_count' => admin_trans('user-month-target.fields.erp_meet_car_count'),
                'meet_car_commission_coefficient' => admin_trans('position-month-salary.fields.meet_car_commission_coefficient'),
                'erp_meet_car_commission' => admin_trans('user-month-target.fields.erp_meet_car_commission'),
                'real_output_value' => admin_trans('user-month-target.fields.real_output_value'),
                'output_value_commission_coefficient' => admin_trans('user-month-target.fields.output_value_commission_coefficient'),
                'output_value_achievement_commission' => admin_trans('user-month-target.fields.output_value_achievement_commission'),
                'output_value_target' => admin_trans('user-month-target.fields.output_value_target'),
                'real_output_values' => admin_trans('user-month-target.fields.real_output_value'),
                'output_value_reach' => admin_trans('user-month-target.fields.output_value_reach'),
                'output_value_score' => admin_trans('user-month-target.fields.output_value_score'),
                'real_maintenance_vehicle' => admin_trans('user-month-target.fields.real_maintenance_vehicle'),
                'maintenance_vehicle_reach' => admin_trans('user-month-target.fields.maintenance_vehicle_reach'),
                'maintenance_vehicle_score' => admin_trans('user-month-target.fields.maintenance_vehicle_score'),
                'kpi_coefficient' => admin_trans('user-month-target.fields.kpi_coefficient'),
                'user_month_award' => admin_trans('user-month-target.fields.user_month_award'),
                'user_month_punish' => admin_trans('user-month-target.fields.user_month_punish'),
                'subtotal_merit_pay' => admin_trans('user-month-target.fields.subtotal_merit_pay'),
                'gross_profit_reach' => admin_trans('user-month-target.fields.gross_profit_reach'),
                'should_merit_pay' => admin_trans('user-month-target.fields.should_merit_pay'),
                'basic_salary' => admin_trans('user-month-target.fields.basic_salary'),
                'total_salary' => admin_trans('user-month-target.fields.total_salary'),
            ];

            $grid->export($titles);

            $grid->export()->rows(function ($rows) {
                foreach ($rows as $index => &$row) {
                    $row->store_title = $row->user->store->title;
                    $row->department_title = $row->user->department->title;
                    $row->position_title = $row->user->position->title;
                    $row->erp_meet_car_count = ErpRepairSettlementService::erpMeetCarCount([
                        'user_erp_id' => $row->user->erp_id,
                        'target_date' => $row->target_date,
                        'store_erp_id' => $row->user->store->erp_id
                    ]);

                    if ($row->positionMonthTarget->is_commission_coefficient_status == DEFAULT_STATUS_SUCCESS) {
                        $row->meet_car_commission_coefficient = $row->positionMonthTarget->meet_car_commission_coefficient;
                    }

                    $row->erp_meet_car_commission = $row->erp_meet_car_count * $row->meet_car_commission_coefficient;
                    $row->real_output_value = UserMonthTargetService::realOutputValue($row);


                    if ($row->positionMonthTarget->is_commission_coefficient_status == DEFAULT_STATUS_SUCCESS) {
                        $row->output_value_commission_coefficient = $row->positionMonthTarget->output_value_commission_coefficient;
                    }

                    $row->output_value_achievement_commission = UserMonthTargetService::outputValueAchievementCommission($row);
                    $row->real_output_values = $row->real_output_value;
                    $row->output_value_reach = UserMonthTargetService::outputValueReach($row);
                    $row->output_value_score = UserMonthTargetService::outputValueScore($row);
                    $row->real_maintenance_vehicle = ErpRepairSettlementService::erpRealMaintenanceVehicle([
                        'user_erp_id' => $row->user->erp_id,
                        'target_date' => $row->target_date,
                        'store_erp_id' => $row->user->store->erp_id
                    ]);
                    $row->maintenance_vehicle_reach = UserMonthTargetService::maintenanceVehicleReach($row);
                    $row->maintenance_vehicle_score = UserMonthTargetService::maintenanceVehicleScore($row);
                    $row->kpi_coefficient = $row->output_value_score + $row->maintenance_vehicle_score;
                    $row->user_month_award = UserMonthTargetService::userMonthAward($row);
                    $row->user_month_punish = UserMonthTargetService::userMonthPunish($row);
                    $row->subtotal_merit_pay = UserMonthTargetService::subtotalMeritPay($row);
                    $row->gross_profit_reach = $row->positionMonthTarget->gross_profit_reach;
                    $row->should_merit_pay = UserMonthTargetService::shouldMeritPay($row);
                    $row->basic_salary = $row->user->basic_salary;
                    $row->total_salary = $row->should_merit_pay + $row->user->basic_salary;
                }

                return $rows;
            });

            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('user.store_id', admin_trans('position-month-salary.fields.store_title'))
                    ->select(Store::all()->pluck('title', 'id'))
                    ->load('user.department_id', 'user-department');
                $filter->equal('user.department_id', admin_trans('position-month-salary.fields.department_title'))->select()->load('user.position_id', 'user-position');
                $filter->equal('user.position_id', admin_trans('position-month-salary.fields.position_title'))->select();
                $filter->equal('target_date')->month();
                $filter->like('user.name', admin_trans('position-month-salary.fields.user_id'));
            });
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, PositionMonthSalary::with(['user', 'positionMonthTarget']), function (Show $show) use ($id) {
            $target = \App\Models\UserMonthTarget::find($id);

            $show->row(function (Show\Row $show) {
                $show->width(6)->id;
                $show->width(6)->target_date;
            });
            $show->row(function (Show\Row $show) {
                $show->width(6)->field('user.name', admin_trans('user-month-target.fields.user_id'));
                $show->width(6)->field('erp_meet_car_count', admin_trans('user-month-target.fields.erp_meet_car_count'))->as(function () use (&$new_erp_meet_car_count) {
                    $this->erp_meet_car_count = ErpRepairSettlementService::erpMeetCarCount([
                        'user_erp_id' => $this->user->erp_id,
                        'target_date' => $this->target_date,
                        'store_erp_id' => $this->user->store->erp_id
                    ]);

                    return $this->erp_meet_car_count;
                });
            });

            $show->row(function (Show\Row $show) {
                $show->width(6)->field('meet_car_commission_coefficient')->as(function () {
                    if ($this->positionMonthTarget->is_commission_coefficient_status == DEFAULT_STATUS_SUCCESS) {
                        $this->meet_car_commission_coefficient = $this->positionMonthTarget->meet_car_commission_coefficient;
                    }

                    return $this->meet_car_commission_coefficient;
                });
                $show->width(6)->field('erp_meet_car_commission', admin_trans('user-month-target.fields.erp_meet_car_commission'))->as(function ($id) {
                    $this->erp_meet_car_commission = $this->erp_meet_car_count * $this->meet_car_commission_coefficient;
                    return $this->erp_meet_car_commission.'元';
                });
            });
            $show->row(function (Show\Row $show) {
                $show->width(6)->field('real_output_value', admin_trans('user-month-target.fields.real_output_value'))->as(function ($id) {
                    $this->real_output_value = ErpRepairSettlementService::erpRealOutputValue([
                        'user_erp_id' => $this->user->erp_id,
                        'target_date' => $this->target_date,
                        'store_erp_id' => $this->user->store->erp_id
                    ]);

                    $score = PositionMonthTargetItem::where('position_month_target_id', $this->position_month_target_id)
                        ->where('user_id', $this->user_id)
                        ->sum('score');

                    $this->real_output_value = ($this->real_output_value + $score)/10000;

                    return $this->real_output_value.'万';
                });
                $show->width(6)->field('output_value_commission_coefficient')->as(function ($id) {
                    if ($this->positionMonthTarget->is_commission_coefficient_status == DEFAULT_STATUS_SUCCESS) {
                        $this->output_value_commission_coefficient = $this->positionMonthTarget->output_value_commission_coefficient;
                    }

                    return $this->output_value_commission_coefficient.'%';
                });
            });
            $show->row(function (Show\Row $show) {
                $show->width(6)->field('output_value_achievement_commission', admin_trans('user-month-target.fields.output_value_achievement_commission'))->as(function ($id) {
                    $this->output_value_achievement_commission = sprintf("%.2f",($this->real_output_value*10000) * ($this->output_value_commission_coefficient/100));
                    return $this->output_value_achievement_commission.'元';
                });
                $show->width(6)->field('output_value_target')->as(function () {
                    return $this->output_value_target.'万';
                });
            });
            $show->row(function (Show\Row $show) {
                $show->width(6)->field('real_output_values', admin_trans('user-month-target.fields.real_output_value'))->as(function ($id) {
                    return $this->real_output_value.'万';
                });
                $show->width(6)->field('output_value_reach', admin_trans('user-month-target.fields.output_value_reach'))->as(function ($id) {
                    $this->output_value_reach = ((($this->real_output_value*10000) / $this->output_value_target) / 100);
                    return sprintf("%.2f",$this->output_value_reach).'%';
                });
            });
            $show->row(function (Show\Row $show) {
                $show->width(6)->field('output_value_score', admin_trans('user-month-target.fields.output_value_score'))->as(function ($id) {
                    if ($this->output_value_reach >= 100) {
                        $this->output_value_score = '0.4';
                    } elseif ($this->output_value_reach >= 90 && $this->output_value_reach <= 100) {
                        $this->output_value_score = '0.35';
                    } else {
                        $this->output_value_score = '0.3';
                    }

                    return $this->output_value_score;
                });
                $show->width(6)->field('maintenance_vehicle_target');
            });
            $show->row(function (Show\Row $show) {
                $show->width(6)->field('real_maintenance_vehicle', admin_trans('user-month-target.fields.real_maintenance_vehicle'))->as(function ($id) {
                    $this->real_maintenance_vehicle = ErpRepairSettlementService::erpRealMaintenanceVehicle([
                        'user_erp_id' => $this->user->erp_id,
                        'target_date' => $this->target_date,
                        'store_erp_id' => $this->user->store->erp_id
                    ]);

                    return $this->real_maintenance_vehicle;
                });
                $show->width(6)->field('maintenance_vehicle_reach', admin_trans('user-month-target.fields.maintenance_vehicle_reach'))->as(function ($id) {
                    $this->maintenance_vehicle_reach = ($this->real_maintenance_vehicle / $this->maintenance_vehicle_target) * 100;
                    return sprintf("%.2f",$this->maintenance_vehicle_reach).'%';
                });
            });
            $show->row(function (Show\Row $show) {
                $show->width(6)->field('maintenance_vehicle_score', admin_trans('user-month-target.fields.maintenance_vehicle_score'))->as(function ($id) {
                    if ($this->maintenance_vehicle_reach >= 100) {
                        $this->maintenance_vehicle_score = '0.7';
                    } elseif ($this->maintenance_vehicle_reach >= 90 && $this->maintenance_vehicle_reach <= 100) {
                        $this->maintenance_vehicle_score = '0.5';
                    } else {
                        $this->maintenance_vehicle_score = '0.4';
                    }

                    return $this->maintenance_vehicle_score;
                });
                $show->width(6)->field('kpi_coefficient', admin_trans('user-month-target.fields.kpi_coefficient'))->as(function ($id) {
                    $this->kpi_coefficient = $this->output_value_score + $this->maintenance_vehicle_score;
                    return $this->kpi_coefficient;
                });
            });
            $show->row(function (Show\Row $show) {
                $show->width(6)->field('user_month_award', admin_trans('user-month-target.fields.user_month_award'))->as(function ($id) {
                    $this->user_month_award = UserMonthAwardPunish::where('position_month_target_id', $this->position_month_target_id)
                        ->where('user_id', $this->user_id)
                        ->where('type', DEFAULT_TYPE_ONE)
                        ->sum('price');

                    return $this->user_month_award;
                });
                $show->width(6)->field('user_month_punish', admin_trans('user-month-target.fields.user_month_punish'))->as(function ($id) {
                    $this->user_month_punish = UserMonthAwardPunish::where('position_month_target_id', $this->position_month_target_id)
                        ->where('user_id', $this->user_id)
                        ->where('type', DEFAULT_TYPE_TWO)
                        ->sum('price');

                    return $this->user_month_punish;
                });
            });
            $show->row(function (Show\Row $show) {
                $show->width(6)->field('subtotal_merit_pay', admin_trans('user-month-target.fields.subtotal_merit_pay'))->as(function ($id) {
                    $this->subtotal_merit_pay = ($this->erp_meet_car_commission + $this->output_value_achievement_commission) * $this->kpi_coefficient + $this->user_month_award - $this->user_month_punish;
                    return $this->subtotal_merit_pay;
                });
                $show->width(6)->field('gross_profit_reach', admin_trans('user-month-target.fields.gross_profit_reach'))->as(function ($id) {
                    $this->gross_profit_reach = $this->positionMonthTarget->gross_profit_reach;
                    return $this->gross_profit_reach.'%';
                });
            });
            $show->row(function (Show\Row $show) {
                $show->width(6)->field('should_merit_pay', admin_trans('user-month-target.fields.should_merit_pay'))->unescape()->as(function ($id) {
                    $this->should_merit_pay = sprintf("%.2f",$this->subtotal_merit_pay * ($this->gross_profit_reach / 100));
                    if ($this->user->probation_period_end_time && ($this->user->probation_period_end_time > $this->target_date.'-01')) {
                        return "<span style='text-decoration:line-through'>{$this->should_merit_pay}</span>";
                    } else {
                        return $this->should_merit_pay;
                    }
                });
                $show->width(6)->field('basic_salary', admin_trans('user-month-target.fields.basic_salary'))->unescape()->as(function ($id) {
                    if ($this->user->probation_period_end_time && ($this->user->probation_period_end_time > $this->target_date.'-01')) {
                        return "<span style='text-decoration:line-through'>{$this->user->basic_salary}</span>";
                    } else {
                        return $this->user->basic_salary;
                    }
                });
            });
            $show->row(function (Show\Row $show) use ($target) {
                $show->width(6)->field('total_salary', admin_trans('user-month-target.fields.total_salary'))->unescape()->as(function ($id) {
                    $total_salary = sprintf("%.2f",$this->should_merit_pay + $this->user->basic_salary);

                    if ($this->user->probation_period_end_time && ($this->user->probation_period_end_time > $this->target_date.'-01')) {
                        return "<span style='text-decoration:line-through'>{$total_salary}</span>";
                    } else {
                        return $total_salary;
                    }
                });
                if ($target->user->probation_period_end_time && ($target->user->probation_period_end_time > $target->target_date.'-01')) {
                    $show->field('user.probation_period_salary', admin_trans('user-month-target.fields.probation_period_salary'));
                }
            });

            $show->panel()
                ->tools(function ($tools) {
                    $tools->disableEdit();
                    $tools->disableList();
                    $tools->disableDelete();
                });
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new PositionMonthSalary(), function (Form $form) {
            $form->display('id');
            $form->text('position_month_target_id');
            $form->text('user_id');
            $form->text('target_date');
            $form->text('meet_car_vehicle_target');
            $form->text('meet_car_commission_coefficient');
            $form->text('output_value_commission_coefficient');
            $form->text('output_value_target');
            $form->text('maintenance_vehicle_target');
        
            $form->display('created_at');
            $form->display('updated_at');
        });
    }
}
